package com.lin.manager.file;

import com.lin.manager.file.oss.LocalOssServiceImpl;
import com.lin.manager.file.oss.OssService;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @作者: 林江
 * @创建时间: 2024/3/22
 * @功能: 文件工厂
 */
public class OssConfig {

    static OssService defaultStrategyService = new LocalOssServiceImpl();
    OssService strategyService = defaultStrategyService;
    List<OssService> decorators;

    public OssConfig() {
        /**
         * 会去加载resources下面的META-INF/services/xxxxxx.xxxxxService接口的文件
         * 这个文件里面装的都是某个的实现类的全路径。
         */
        ServiceLoader<OssService> load = ServiceLoader.load(OssService.class);
        this.decorators = new ArrayList<>();
        for (OssService service : load) {
            decorators.add(service);
        }
    }

    @Bean
    public OssService ossService() {
        return getStrategyService();
    }

    public OssService getStrategyService() {
        if (decorators != null) {
            for (OssService decorator : decorators) {
                decorator.next(strategyService);
                this.strategyService = decorator;
            }
        }
        return strategyService;
    }
}
